package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器（只有登录之后，才能操作）
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    //在controller的handler方法之前运行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //TODO
        /*if (request.getRemoteAddr().startsWith("192")) {
            R<String> r = R.error("NOTLOGIN");
            response.getWriter().write(JSON.toJSONString(r));
            return false;
        }*/

        //1. 判断员工是否登录，从session中获取用户信息id
        Object employee = request.getSession().getAttribute("employee");
        if (employee != null) {
            //往当前线程存入一个数据
            BaseContext.setCurrentId((Long) employee);
            return true;
        }

        //2. 判断用户是否登录，从session中获取用户信息id
        Object user = request.getSession().getAttribute("user");
        if (user != null) {
            //往当前线程存入一个数据
            BaseContext.setCurrentId((Long) user);
            return true;
        }

        //3. 说明没有登录，响应未登录信息给客户端
        R<String> r = R.error("NOTLOGIN");
        response.getWriter().write(JSON.toJSONString(r));
        return false;
    }


    //在handler执行完之后操作（资源释放）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        BaseContext.remove();
    }


}
